<template>
    <div ref="container" class="scene-container"></div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

const container = ref(null);
const gridSize = { width: 10, height: 6 }; // 10x6的网格
const cellSize = 1; // 每个格子大小
const graph = [];
const mesh = [];


var length = 36;
var ws = 2;

let scene  = null


onMounted(() => {
    // 初始化场景
    scene = new THREE.Scene();
    const axesHelper = new THREE.AxesHelper(100);
    axesHelper.position.set(0, 0, 10)
    scene.add(axesHelper)

    const camera = new THREE.PerspectiveCamera(
        40,
        container.value.clientWidth / container.value.clientHeight,
        0.1,
        1000
    );
    camera.position.set(60, 35, 60);
    camera.lookAt(0, 5, -20);

    var textureLoader = new THREE.TextureLoader();
					var cubeMaterial = new THREE.MeshStandardMaterial({
						map: textureLoader.load('/static/1750409744743.png'),
					});
					cubeMaterial.map.wrapS = THREE.RepeatWrapping;
					cubeMaterial.map.wrapT = THREE.RepeatWrapping;
					cubeMaterial.map.repeat.set(18, 18)
					// 创建地平面并设置大小
					var planeGeometry = new THREE.PlaneGeometry(500, 500);
					var plane = new THREE.Mesh(planeGeometry, cubeMaterial);
 
					// 设置平面位置并旋转
					plane.rotation.x = -0.5 * Math.PI;
					plane.position.x = 0;
					plane.position.z = 0;
					// return plane;

                    var geometry = new THREE.BoxGeometry();
                    console.log(geometry,'我不着地所杀了')
					geometry.groups.push(new THREE.Vector3(0, 0, 0));
					geometry.groups.push(new THREE.Vector3(length, 0, 0));
 
					for (var i = 0; i <= length / ws; i++) {
						var material = new THREE.LineBasicMaterial({
							color: 0x808080
						});
						var line = new THREE.Line(geometry, material);
						line.position.z = i * ws;
						scene.add(line);
 
						var line = new THREE.Line(geometry, material);
						line.position.x = i * ws;
						line.position.z = length;
						line.rotation.y = 90 * Math.PI / 180;
						scene.add(line);
					}

                    for (var i = 0; i < length / ws; i++) {
						var nodeRow = [];
						for (var j = 0; j < length / ws; j++) {
							nodeRow.push(1);
						}
						graph.push(nodeRow);

                    }

                    console.log(graph,'我是大撒')




   
    //添加两个平行光
    // const directionalLight1 = new THREE.DirectionalLight(0xffffff, 1.5);
    // directionalLight1.position.set(300, 300, 600)
    // scene.add(directionalLight1);
    // const directionalLight2 = new THREE.DirectionalLight(0xffffff, 1.5);
    // directionalLight2.position.set(600, 200, 600)
    // scene.add(directionalLight2);

    // 添加地板
    // let floorGeometry = new THREE.PlaneGeometry(500, 500);
    // let floorMaterial = new THREE.MeshPhysicalMaterial({ color: '#FFFFFF' });
    // let textureFloor = new THREE.TextureLoader().load('/static/1750409744743.png', function (texture) {
    //     texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
    // })
    // floorMaterial.map = textureFloor
    // let floor = new THREE.Mesh(floorGeometry, floorMaterial);

    // scene.add(floor)




    // floor.geometry.computeBoundingBox(); // 注意
    // const box = new THREE.Box3().setFromObject(floor); // 获取网格的边界框
    // const center = new THREE.Vector3();
    // box.getCenter(center); // 计算中心点坐标

    // // 步骤2：移动几何体至原点
    // floor.position.sub(center); // 减去中心偏移量，使网格中心对齐(0,0,0)

    // // floor.name = '地板';

    // // 调整相机和轨道控制器（可选）
    // camera.position.set(0, 0, 200); // 相机位置，确保视角覆盖原点
    // camera.lookAt(0, 0, 0);

    // 计算包围盒
    // const boxsd = new THREE.Box3().setFromObject(floor);
    // const min = boxsd.min; // 包含最小x/y/z坐标
    // const max = boxsd.max; // 包含最大x/y/z坐标
    // console.log(
    // `X范围: ${min.x} 到 ${max.x}`,
    // `Y范围: ${min.y} 到 ${max.y}`
    // );



    // // 计算中心点
    // const boundingBox = floorGeometry.boundingBox;
    // const center = new THREE.Vector3();
    // boundingBox.getCenter(center);


    // //  floor.rotation.x = -Math.PI / 2;

    // floor.position.sub(center);

    // 2. 添加网格线
    // const gridHelper = new THREE.GridHelper(
    //     10 * cellSize,
    //     10,
    //     0x000000,
    //     0x000000
    // );
    // gridHelper.position.y = 0.01; // 稍微抬高避免z-fighting
    // scene.add(gridHelper);


    // floor.position.sub(center);
    // camera.position.z = 5;


    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(container.value.clientWidth, container.value.clientHeight);
    renderer.setClearColor('#AAAAAA', 1.0);
    container.value.appendChild(renderer.domElement);

    const controls = new OrbitControls(camera, renderer.domElement);
    controls.minDistance = 100;
    controls.maxDistance = 1000;
    controls.target.set(0, 0, 0); // 控制器焦点设为原点



    // console.log(floor.endX,'我是x')
    // // 添加3个障碍物
    // const particlesGeometry1 = new THREE.BoxGeometry(10,20, 10);
    // let material = new THREE.MeshPhongMaterial({
    //     color: '#FF0000', // 设置颜色
    //     shininess: 20 // 设置高光大小，范围为0到128，默认值为30
    // });
    // let box1 = new THREE.Mesh(particlesGeometry1, material, 0);
    // console.log(center,'我是中心点')
    // box1.position.set(-20,-60,5)
    // scene.add(box1);



    // const particlesGeometry2 = new THREE.BoxGeometry(21,30, 10);
    // let box2 = new THREE.Mesh(particlesGeometry2, material, 0);
    // box2.position.set(0,0, 5)
    // scene.add(box2);

    // const particlesGeometry3 = new THREE.BoxGeometry(20,10, 10);
    // let box3 = new THREE.Mesh(particlesGeometry3, material, 0);
    // box3.position.set(40,20,5)
    // scene.add(box3);


    initGrid();




    // camera.lookAt(200, 150, 0);
    // controls.update();

    // const controls = new OrbitControls(camera, renderer.domElement);
    // controls.enableDamping = true;
    // controls.dampingFactor = 0.5;
    // // 视角最小距离
    // controls.minDistance = 100;
    // // 视角最远距离
    // controls.maxDistance = 1000;
    // // 最大角度
    // controls.target = new THREE.Vector3(600, 150, 0);
    // camera.position.set(600, 150, 400);
    // camera.lookAt(200, 150, 0);

    // 创建网格平面
    // createGridPlane(scene);

    // renderer.render(scene, camera);

    // // 动画循环
    const animate = () => {
        requestAnimationFrame(animate);
        renderer.render(scene, camera);
    };
    animate();

    const raycaster = new THREE.Raycaster();
    const mouse = new THREE.Vector2();

    const onMouseClick = (event) => {
        // 归一化鼠标坐标（-1到1）
        mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
        mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
        
        // 更新射线方向
        raycaster.setFromCamera(mouse, camera);
        
        // 检测与场景物体的交点
        const intersects = raycaster.intersectObjects(scene.children);
        
        if (intersects.length > 0) {
            addPoint(intersects[0].point);
        }
    };

    window.addEventListener('click', onMouseClick);

});




function initGrid() {
					for (var i = 0; i < length / ws; i++) {
						var nodeRow = [];
						for (var j = 0; j < length / ws; j++) {
							var salt = Math.random() * 7;
							if (salt > 2) {
								nodeRow.push(1);
							} else {
								nodeRow.push(0);
							}
							if (salt <= 2) {
								var cube = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1), new THREE.MeshBasicMaterial({
									color: 0xC0C0C0
								}));
								let x = ws * j + ws / 2;
								let z = ws * i + ws / 2;
								cube.position.set(x, 1.2, z);
								scene.add(cube);
								mesh.push(cube);
							}
						}
						graph.push(nodeRow);
					}
    }


let points = []; // 存储起点和终点

function addPoint(position) {
  if (points.length >= 2) {
    // 如果已经有两个点了，就不再添加 开始计算路径距离
    console.log(points,'我是点位')
    return; // 最多两个点
  }
  
  const pointMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00  });
  // 创建标记球体
  const sphere = new THREE.Mesh(
    new THREE.SphereGeometry(3, 32, 16),
    pointMaterial
  );
  sphere.position.copy(position);
  scene.add(sphere);
  // 保存点对象
  points.push({
    obj: sphere,
    position: position
  });
  
  // 添加标签
  if (points.length === 1) {
    // createLabel(sphere, "起点");
  } else {
    // createLabel(sphere, "终点");
    // 添加两点间的连线
    createConnectionLine(points[0].position, points[1].position);
  }
}

function createConnectionLine(start, end) {
  const lineGeometry = new THREE.BufferGeometry().setFromPoints([start, end]);
  const lineMaterial = new THREE.LineBasicMaterial({ color: 'green', linewidth: 5,
	linecap: 'round', //ignored by WebGLRenderer
	linejoin:  'round' //ignored by WebGLRenderer
});
  const line = new THREE.Line(lineGeometry, lineMaterial);
  scene.add(line);
}



// 开始计算路线
function getPaht(){

      let judgeBegin = judgeObstacle(this.beginPoint.x,this.beginPoint.y)
      let judgeEnd = judgeObstacle(this.endPoint.x,this.endPoint.y)
      if("xy" === judgeBegin.xy || "xy" === judgeEnd.xy){
        console.log("出发和结束点不能再障碍物里")
        return "出发和结束点不能再障碍物里"
      }
      this.removeOnce();

      let pointList = [];
      let distanceX = this.endPoint.x - this.beginPoint.x;
      let abxX = distanceX/Math.abs(distanceX)
      let distanceY = this.endPoint.y - this.beginPoint.y;
      let abxY = distanceY/Math.abs(distanceY)
      let countX = Math.abs(distanceX) / 5;
      let countY = Math.abs(distanceY) / 5;
      let tempPoint = {
        x:this.beginPoint.x,
        y:this.beginPoint.y
      }
      for (let i = 0; i < countX; i++) {
        tempPoint.x = parseInt(tempPoint.x) + 5 * abxX
        if(countY>0){
          countY --;
          tempPoint.y = parseInt(tempPoint.y) + 5 * abxY
        }
        let judgeResult = this.judgeObstacle(tempPoint.x, tempPoint.y);
        if("x" === judgeResult.xy){
          if(i === countX){
            tempPoint.x = parseInt(tempPoint.x) + 5 * abxX
          }else{
            if(countY>0){
              countY ++;
              tempPoint.y = tempPoint.y - 5 * abxY
            }
          }
          console.log("在x里")
        }
        else if("y" === judgeResult.xy){
          if(countY === 0){
            tempPoint.y = parseInt(tempPoint.y) + 5 * abxX
          }else{
            i --;
            tempPoint.x = tempPoint.x - 5 * abxX
          }
          console.log("在y里，")
        }
        console.log(tempPoint.x + " " + tempPoint.y)
        let point = {x:tempPoint.x,y:tempPoint.y,z:2}
        pointList.push(point)
      }
      let point = {x:this.endPoint.x,y:this.endPoint.y,z:2}
      pointList.push(point)
      this.drawPath(pointList);

}

// 判断障碍物

function judgeObstacle(x,y){ //判断障碍物
      let result = {
        xy:"",
        distance:0,
        box:null
      };
      if(x>=this.box1.beginX && x<=this.box1.endX){
        result.xy = "x";result.distance = Math.abs(this.box1.beginX-x);result.box = this.box1;
      }else if (x>=this.box2.beginX && x<=this.box2.endX){
        result.xy = "x";result.distance = Math.abs(this.box2.beginX-x);result.box = this.box2;
      }else if (x>=this.box3.beginX && x<=this.box3.endX){
        result.xy = "x";result.distance = Math.abs(this.box3.beginX-x);result.box = this.box2;
      }

      if(y>=this.box1.beginY && y<=this.box1.endY){
        result.xy = "y";result.distance = Math.abs(this.box1.beginX-x);result.box = this.box1;
      }else if(y>=this.box2.beginY && y<=this.box2.endY){
        result.xy = "y";result.distance = Math.abs(this.box2.beginX-x);result.box = this.box2;
      }else if(y>=this.box3.beginY && y<=this.box3.endY){
        result.xy = "y";result.distance = Math.abs(this.box3.beginX-x);result.box = this.box3;
      }
      if(x>=this.box1.beginX && x<=this.box1.endX && y>=this.box1.beginY && y<=this.box1.endY){
        result.xy = "xy";
      }else if (x>=this.box2.beginX && x<=this.box2.endX && y>=this.box2.beginY && y<=this.box2.endY){
        result.xy = "xy";
      }else if (x>=this.box3.beginX && x<=this.box3.endX && y>=this.box3.beginY && y<=this.box3.endY){
        result.xy = "xy";
      }
      return result;
}


// 添加障碍物
// function obstacle() {

    

// }



// const clickPosition = ref({ x: 0, y: 0 });
// const raycaster = new THREE.Raycaster();
// const mouse = new THREE.Vector2();



// function createGridPlane(scene) {
//     // 1. 创建基础平面
//     const planeGeometry = new THREE.PlaneGeometry(
//         gridSize.width * cellSize,
//         gridSize.height * cellSize
//     );
//     const planeMaterial = new THREE.MeshBasicMaterial({
//         color: 0xdddddd,
//         side: THREE.DoubleSide,
//         transparent: true,
//         opacity: 0.5
//     });
//     const plane = new THREE.Mesh(planeGeometry, planeMaterial);
//     plane.rotation.x = -Math.PI / 2;
//     scene.add(plane);

//     // 2. 添加网格线
//     const gridHelper = new THREE.GridHelper(
//         gridSize.width * cellSize,
//         gridSize.width,
//         0x000000,
//         0x000000
//     );
//     gridHelper.position.y = 0.01; // 稍微抬高避免z-fighting
//     scene.add(gridHelper);

//     // 3. 添加每个小格子（可选）
//     for (let x = 0; x < gridSize.width; x++) {
//         for (let y = 0; y < gridSize.height; y++) {
//             const cellGeometry = new THREE.PlaneGeometry(cellSize - 0.1, cellSize - 0.1);
//             const cellMaterial = new THREE.MeshBasicMaterial({
//                 color: Math.random() * 0xffffff,
//                 side: THREE.DoubleSide
//             });
//             const cell = new THREE.Mesh(cellGeometry, cellMaterial);
//             cell.position.set(
//                 x * cellSize - (gridSize.width * cellSize) / 2 + cellSize / 2,
//                 0.02,
//                 y * cellSize - (gridSize.height * cellSize) / 2 + cellSize / 2
//             );
//             cell.rotation.x = -Math.PI / 2;
//             scene.add(cell);
//         }
//     }
// }
</script>

<style scoped>
.scene-container {
    width: 100%;
    height: 100vh;
}
</style>
